package com.huashi.dealer.modular.controller.api.goods;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huashi.dealer.commonEntity.Goods;
import com.huashi.dealer.commonEntity.User;
import com.huashi.dealer.core.page.PageFactory;
import com.huashi.dealer.core.util.SaTokenUtil;
import com.huashi.dealer.core.pojo.CommonResult;
import com.huashi.dealer.modular.business.goods.bo.GoodsListBo;
import com.huashi.dealer.modular.business.goods.service.GoodsService;
import com.huashi.dealer.modular.business.goods.param.GoodsResponseParam;
import com.huashi.dealer.modular.business.goods.param.GoodsDetailVo;
import com.huashi.dealer.modular.business.goods.vo.GoodsListVo;
import com.huashi.dealer.modular.business.user.mapper.UserMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * API商品控制器
 *
 * @author 谭陈强
 * @since 2025-07-30
 */
@Tag(name = "API商品控制器")
@RestController("apiGoodsController")
@RequestMapping("/api/goods")
@Validated
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    @Resource
    private UserMapper userMapper;

    /**
     * 商品分类
     */
    @GetMapping("/category/index")
    @Operation(summary = "商品分类")
    public CommonResult<GoodsResponseParam> getCategoryList() {
        try {
            GoodsResponseParam responseParam = goodsService.getCategoryList();
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取商品分类失败：" + e.getMessage());
        }
    }

    /**
     * 商品列表（POST方法，使用GoodsListBo）
     */
    @GetMapping("/lists")
    @Operation(summary = "商品列表")
    public CommonResult<Page<GoodsListVo>> getGoodsList(GoodsListBo bo) {
        Page<Goods> page = PageFactory.defaultPage();
        try {
            // 获取用户信息，用于经销商商品权限过滤
            Long userId = SaTokenUtil.getLoginId();
            if (userId != null) {
                User user = userMapper.selectById(userId);
                if (user != null) {
                    bo.setUserId(user.getUserId());
                    bo.setGoodsIds(user.getGoodsIds());
                }
            }

            Page<GoodsListVo> result = goodsService.getGoodsList(bo,page);
            return CommonResult.data(result);
        } catch (Exception e) {
            return CommonResult.error("获取商品列表失败：" + e.getMessage());
        }
    }

    /**
     * 商品列表（GET方法，兼容旧版本）
     */
//    @GetMapping("/lists")
//    @Operation(summary = "商品列表")
//    public CommonResult<GoodsResponseParam> getGoodsList(@RequestParam(required = false) Long categoryId,
//                                                          @RequestParam(required = false) String search,
//                                                          @RequestParam(required = false) Integer isNewProduct,
//                                                          @RequestParam(required = false) Integer isHotSellingItem,
//                                                          @RequestParam(required = false) Integer page,
//                                                          @RequestParam(required = false) Integer listRows) {
//        try {
//            GoodsResponseParam responseParam = goodsService.getGoodsList(categoryId, search, isNewProduct, isHotSellingItem, page, listRows);
//            return CommonResult.data(responseParam);
//        } catch (Exception e) {
//            return CommonResult.error("获取商品列表失败：" + e.getMessage());
//        }
//    }

    /**
     * 商品详情
     */
    @GetMapping("/detail/{goodsId}")
    @Operation(summary = "商品详情")
    public CommonResult<GoodsDetailVo> getGoodsDetail(@PathVariable Long goodsId) {
        try {
            // 获取用户信息，用于经销商商品权限过滤
            Long userId = SaTokenUtil.getLoginId();
            User user = null;
            if (userId != null) {
                user = userMapper.selectById(userId);
            }

            GoodsDetailVo responseParam = goodsService.getGoodsDetail(goodsId, user);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取商品详情失败：" + e.getMessage());
        }
    }

    /**
     * 扫码商品详情
     */
    @GetMapping("/barCodeDetail/{barCode}")
    @Operation(summary = "扫码商品详情")
    public CommonResult<List<GoodsDetailVo>> getBarCodeDetail(@PathVariable String barCode) {
        try {
            return CommonResult.data(goodsService.getBarCodeDetail(barCode));
        } catch (Exception e) {
            return CommonResult.error("获取扫码商品详情失败：" + e.getMessage());
        }
    }


    /**
     * 生成商品海报
     */
    @GetMapping("/poster/{goodsId}")
    @Operation(summary = "生成商品海报")
    public CommonResult<GoodsResponseParam> generateGoodsPoster(@PathVariable Long goodsId,
                                                                 @RequestParam(required = false) String token) {
        try {
            GoodsResponseParam responseParam = goodsService.generateGoodsPoster(goodsId, token);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("生成商品海报失败：" + e.getMessage());
        }
    }

    /**
     * 商品搜索
     */
    @GetMapping("/search")
    @Operation(summary = "商品搜索")
    public CommonResult<GoodsResponseParam> searchGoods(@RequestParam String keyword,
                                                         @RequestParam(required = false) Long categoryId,
                                                         @RequestParam(required = false) Integer page,
                                                         @RequestParam(required = false) Integer listRows) {
        try {
            GoodsResponseParam responseParam = goodsService.searchGoods(keyword, categoryId, page, listRows);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("商品搜索失败：" + e.getMessage());
        }
    }

    /**
     * 热门商品
     */
    @GetMapping("/hot")
    @Operation(summary = "热门商品")
    public CommonResult<GoodsResponseParam> getHotGoods(@RequestParam(required = false) Integer limit) {
        try {
            GoodsResponseParam responseParam = goodsService.getHotGoods(limit);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取热门商品失败：" + e.getMessage());
        }
    }

    /**
     * 新品推荐
     */
    @GetMapping("/new")
    @Operation(summary = "新品推荐")
    public CommonResult<GoodsResponseParam> getNewGoods(@RequestParam(required = false) Integer limit) {
        try {
            GoodsResponseParam responseParam = goodsService.getNewGoods(limit);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取新品推荐失败：" + e.getMessage());
        }
    }

    /**
     * 商品推荐
     */
    @GetMapping("/recommend")
    @Operation(summary = "商品推荐")
    public CommonResult<GoodsResponseParam> getRecommendGoods(@RequestParam(required = false) Long goodsId,
                                                               @RequestParam(required = false) Integer limit) {
        try {
            GoodsResponseParam responseParam = goodsService.getRecommendGoods(goodsId, limit);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取商品推荐失败：" + e.getMessage());
        }
    }
} 